<template>
  <el-select 
    ref="select"
    @focus="$emit('focusNameChange', data.name)"
    @blur="$emit('focusNameChange', '')"
    @visible-change="getSelectAsyncOptions(data)"
    @change="selectChange"
    :loading="data.asyncItems && !data.asyncOptions"
    v-model="data.value"
    :placeholder="data.placeholder">
    <!-- 数据异步加载 -->
    <el-option 
      v-if="data.asyncItems"
      v-for="item in data.asyncOptions"
      :key="item.value"
      :label="item.label"
      :value="item.value"></el-option>
    <!-- 选择数据已存在 -->
    <el-option
      v-if="data.items"
      v-for="item in data.items"
      :key="item.value"
      :label="item.label"
      :value="item.value"></el-option>
  </el-select>
</template>

<script>
export default {
  data () {
    return {
      data: {}
    }
  },
  props: {
    metaData: Object,
    from: {  // all or commmon
      type: String,
      default: 'common'
    }
  },
  watch: {
    metaData: {
      immediate: true,
      handler (v) {
        if (v && Object.keys(v).length) {
          this.data = v
          this.$nextTick(() => {
            this.from === 'common' &&
              this.$refs['select'] &&
              this.$refs['select'].focus()
          })
        }
      }
    }
  },
  methods: {
    // 选择改变
    selectChange () {
      const options = this.data.asyncItems ? this.data.asyncOptions : this.data.items
      this.data.label = options.find(i => i.value === this.data.value).label
      this.$emit('selectChange', this.data)
      this.$nextTick(() => { if (this.from === 'common') this.data.value = '' })
    },
    // 下拉框选项异步获取
    async getSelectAsyncOptions (data) {
      if (data.asyncItems && !data.asyncOptions) {
        const [ err, res ] = await data.asyncItems.getAsyncItems()
        if (err) return this.$message.error('获取下拉框数据失败')
        this.$set(data, 'asyncOptions', data.asyncItems.asyncItemsHandler(res))
      }
    }
  }
}
</script>
